package com.villaday.idf.custom.pop;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.adapter.Data;
import com.villaday.idf.model3.HashPrice;
import com.villaday.idf.model3.HashStates;
import com.villaday.idf.model3.HashStatesEntity;
import com.villaday.idf.model3.StatesPostEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DateUtils;
import com.villaday.idf.util.ImageViewUtils;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PopularUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import razerdp.basepopup.BasePopupWindow;

public class HouseManagePop extends BasePopupWindow implements View.OnClickListener {

    private Context mContext;
    private OnBtnClickListener onBtnClickListener;
    private boolean isFirst = true;
    private final TextView mTvTimeMore0;
    private final TextView mTvTimeMore1;
    private final List<HashStatesEntity.BodyBean.MonthsBean> mMonths;
    private int mTotalHouse = 0;//总库存
    private int mHaveHouse = 0;//已用库存
    private int mNotHouse = 0;//未用
    private TextView mTvTotalNum;
    private TextView mTvLeftNum;
    private TextView mTvRightNum;
    private ImageView mIvLeftReduce;
    private ImageView mIvLeftAdd;
    private ImageView mIvRightReduce;
    private ImageView mIvRightAdd;
    private String timeValue = "";
    private Calendar selectedDate = Calendar.getInstance();
    private String mStartDate;
    private String mEndDate;
    private int mType;
    private List<String> dateString = new ArrayList<>();
    private String mHouseId;
    private Calendar mDataEndDate;
    private boolean isClose = true;

    public HouseManagePop(Context context, int type, String houseId, String name, String data) {
        super(context);
        mContext = context;
        PopularUtil.buildAnimal();
        setBackground(0);
        setOutSideDismiss(true);
        setKeepSize(true);
        setPopupFadeEnable(false);
        setBackgroundColor(Color.parseColor("#B3000000"));
        setBlurBackgroundEnable(true);

        mType = type;
        mHouseId = houseId;
        TextView tvTitle = findViewById(R.id.tv_hmp_title);
        TextView tvName = findViewById(R.id.tv_hmp_name);
        TextView tvTime = findViewById(R.id.tv_hmp_time);
        mTvTimeMore0 = findViewById(R.id.tv_hm_time_more0);
        mTvTimeMore1 = findViewById(R.id.tv_hm_time_more1);
        LinearLayout llMoreTime = findViewById(R.id.ll_hm_more_time);
        TextView tvTotalTitle = findViewById(R.id.tv_hmp_total_title);
        TextView tvCancel = findViewById(R.id.tv_hmp_cancel);
        TextView tvConfirm = findViewById(R.id.tv_hmp_confirm);
        ImageView ivClose = findViewById(R.id.iv_hmp_close);


        mTvTotalNum = findViewById(R.id.tv_total_num);

        mIvLeftReduce = findViewById(R.id.iv_left_reduce);
        mTvLeftNum = findViewById(R.id.tv_left_num);
        mIvLeftAdd = findViewById(R.id.iv_left_add);


        mIvRightReduce = findViewById(R.id.iv_right_reduce);
        mTvRightNum = findViewById(R.id.tv_right_num);
        mIvRightAdd = findViewById(R.id.iv_right_add);

        tvCancel.setOnClickListener(this);
        tvConfirm.setOnClickListener(this);
        ivClose.setOnClickListener(this);
        mTvTimeMore0.setOnClickListener(this);
        mTvTimeMore1.setOnClickListener(this);
        mIvLeftReduce.setOnClickListener(this);
        mIvLeftAdd.setOnClickListener(this);
        mIvRightReduce.setOnClickListener(this);
        mIvRightAdd.setOnClickListener(this);

        tvName.setText(name);
        mMonths = new Gson().fromJson(data, HashStatesEntity.BodyBean.class).getMonths();

        switch (mType) {
            case 0://设置房态
                getTimeNum(0);
                if (timeValue.length() > 1) {
                    timeValue = timeValue.substring(0, timeValue.length() - 1);
                }
                tvTime.setText(timeValue);
                break;
            case 1://批量设置房态
                tvTitle.setText("批量设置房态");
                llMoreTime.setVisibility(View.VISIBLE);
                mStartDate = DateUtils.long2Data(System.currentTimeMillis());
                mEndDate = DateUtils.getdate(selectedDate.getActualMaximum(selectedDate.DAY_OF_MONTH));
                getTimeNum(1);
                mTvTimeMore0.setText(mStartDate);
                mTvTimeMore1.setText("/" + mEndDate);
                tvTotalTitle.setText("批量操作的日期:");
                tvTime.setVisibility(View.GONE);
                break;
        }
        setShowHide();
    }


    /**
     * 计算相关库存
     *
     * @param type 判定是否为批量
     */
    public void getTimeNum(int type) {
        List<HashStatesEntity.BodyBean.MonthsBean.DaysBean> list = new ArrayList<>();
        for (int i = 0; i < mMonths.size(); i++) {
            for (int j = 0; j < mMonths.get(i).getDays().size(); j++) {
                if (!mMonths.get(i).getDays().get(j).getText().equals("default")) {
                    list.add(mMonths.get(i).getDays().get(j));
                }

                switch (type) {
                    case 0:
                        if (mMonths.get(i).getDays().get(j).isSelect()) {
                            mTotalHouse = mMonths.get(i).getDays().get(j).getTotalQuantity();
//                            mHaveHouse = mMonths.get(i).getDays().get(j).getUsedQuantity();
                            dateString.add(mMonths.get(i).getDays().get(j).getDate());
                        }
                        break;
                    case 1:
                        if (!mMonths.get(i).getDays().get(j).getText().equals("default") && DateUtils.string2Data(mMonths.get(i).getDays().get(j).getDate()) >= DateUtils.string2Data(mStartDate)
                                && DateUtils.string2Data(mMonths.get(i).getDays().get(j).getDate()) <= DateUtils.string2Data(mEndDate)) {
                            mTotalHouse = mMonths.get(i).getDays().get(j).getTotalQuantity();
//                            mHaveHouse =  mMonths.get(i).getDays().get(j).getUsedQuantity();
                        }
                        break;
                }
            }
        }

        if (type == 0) {
            LogUtil.jLog().e(new Gson().toJson(list));
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).isSelect()) {
                    if (i + 2 < list.size() && list.get(i + 1).isSelect() && list.get(i + 2).isSelect()) {
                        String startData = list.get(i).getDate();
                        String endDate = null;
                        boolean isOk = true;
                        for (int j1 = i; j1 < list.size(); j1++) {
                            if (isOk) {
                                if (!list.get(j1).isSelect()) {
                                    i = j1 - 1;
                                    endDate = list.get(i).getDate();
                                    isOk = false;
                                }

                                if ((j1 == list.size() - 1 && list.get(j1).isSelect())) {
                                    i = j1;
                                    endDate = list.get(i).getDate();
                                    isOk = false;
                                }
                            }
                        }
                        timeValue = timeValue + DateUtils.data2Data(startData) + "—" + DateUtils.data2Data(endDate) + "、";
                    } else {
                        timeValue = timeValue + DateUtils.data2Data(list.get(i).getDate()) + "、";
                    }
                }
            }

        }


        mNotHouse = mTotalHouse - mHaveHouse;
        mTvTotalNum.setText("房源总库存：" + mTotalHouse);
        mTvLeftNum.setText(mHaveHouse + "");
        mTvRightNum.setText(mNotHouse + "");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_hmp_cancel://直接关房
                isClose = true;
                setPostDate(1);
                break;
            case R.id.tv_hmp_confirm://保存
                isClose = false;
                setPostDate(2);
                break;
            case R.id.iv_hmp_close:
                dismiss();
                break;
            case R.id.tv_hm_time_more0://起始时间
            case R.id.tv_hm_time_more1://结束时间
                isFirst = true;
//                dismiss();
                initStartTime();
                break;
            case R.id.iv_left_reduce://已售库存-
                if (mHaveHouse > 1) {
                    mHaveHouse--;
                    mNotHouse = mTotalHouse - mHaveHouse;
                    mTvLeftNum.setText(mHaveHouse + "");
                    mTvRightNum.setText(mNotHouse + "");
                } else {
                    mHaveHouse = 0;
                    mNotHouse = mTotalHouse;
                    mTvLeftNum.setText("0");
                    mTvRightNum.setText(mNotHouse + "");
                }
                setShowHide();
                break;
            case R.id.iv_left_add://已售库存+
                if (mHaveHouse < mTotalHouse) {
                    mHaveHouse++;
                    mNotHouse = mTotalHouse - mHaveHouse;
                    mTvLeftNum.setText(mHaveHouse + "");
                    mTvRightNum.setText(mNotHouse + "");
                } else {
                    mHaveHouse = mTotalHouse;
                    mNotHouse = 0;
                    mTvLeftNum.setText(mHaveHouse + "");
                    mTvRightNum.setText(mNotHouse + "");
                }
                setShowHide();
                break;
            case R.id.iv_right_reduce://剩余库存-
                if (mNotHouse > 1) {
                    mNotHouse--;
                    mHaveHouse = mTotalHouse - mNotHouse;
                    mTvLeftNum.setText(mHaveHouse + "");
                    mTvRightNum.setText(mNotHouse + "");
                } else {
                    mNotHouse = 0;
                    mHaveHouse = mTotalHouse;
                    mTvRightNum.setText("0");
                    mTvLeftNum.setText(mHaveHouse + "");
                }
                setShowHide();
                break;
            case R.id.iv_right_add://剩余库存+
                if (mNotHouse < mTotalHouse) {
                    mNotHouse++;
                    mHaveHouse = mTotalHouse - mNotHouse;
                    mTvLeftNum.setText(mHaveHouse + "");
                    mTvRightNum.setText(mNotHouse + "");
                } else {
                    mHaveHouse = 0;
                    mNotHouse = mTotalHouse;
                    mTvLeftNum.setText(mHaveHouse + "");
                    mTvRightNum.setText(mNotHouse + "");
                }
                setShowHide();
                break;
        }


    }


    /**
     * 控制—+显示方式
     */
    public void setShowHide() {
        if (mHaveHouse == 0) {
            ImageViewUtils.setImageViewColor(mIvLeftReduce, Color.argb(88, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvLeftAdd, Color.argb(255, 0, 0, 0));

            ImageViewUtils.setImageViewColor(mIvRightReduce, Color.argb(255, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvRightAdd, Color.argb(88, 0, 0, 0));
        } else if (mHaveHouse == mTotalHouse) {
            ImageViewUtils.setImageViewColor(mIvLeftReduce, Color.argb(255, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvLeftAdd, Color.argb(88, 0, 0, 0));

            ImageViewUtils.setImageViewColor(mIvRightReduce, Color.argb(88, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvRightAdd, Color.argb(255, 0, 0, 0));
        } else if (mNotHouse == mTotalHouse) {
            ImageViewUtils.setImageViewColor(mIvLeftReduce, Color.argb(88, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvLeftAdd, Color.argb(255, 0, 0, 0));

            ImageViewUtils.setImageViewColor(mIvRightReduce, Color.argb(255, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvRightAdd, Color.argb(88, 0, 0, 0));
        } else if (mNotHouse == 0) {
            ImageViewUtils.setImageViewColor(mIvLeftReduce, Color.argb(255, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvLeftAdd, Color.argb(88, 0, 0, 0));

            ImageViewUtils.setImageViewColor(mIvRightReduce, Color.argb(88, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvRightAdd, Color.argb(255, 0, 0, 0));
        } else {
            ImageViewUtils.setImageViewColor(mIvLeftReduce, Color.argb(255, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvLeftAdd, Color.argb(255, 0, 0, 0));

            ImageViewUtils.setImageViewColor(mIvRightReduce, Color.argb(255, 0, 0, 0));
            ImageViewUtils.setImageViewColor(mIvRightAdd, Color.argb(255, 0, 0, 0));
        }


    }


    /**
     * 提交后台修改数据
     *
     * @param action
     */
    private void setPostDate(final int action) {
        Map<String, Object> map = new HashMap<>();
        HashStates hashStates = new HashStates();
        hashStates.setAction(action);
        hashStates.setDates(dateString);
        hashStates.setStartDate(mStartDate);
        hashStates.setEndDate(mEndDate);
        hashStates.setTotalQuantity(mTotalHouse);
        hashStates.setUsedQuantity(mHaveHouse);
        LogUtil.jLog().e(new Gson().toJson(hashStates));
        OkHttpUtil.postJson(mContext, String.format(Constant.URL.hashStates, SharedPreferencesUtil.getRoleInfoId(mContext), mHouseId), hashStates, map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    StatesPostEntity statesPostEntity = new Gson().fromJson(json, StatesPostEntity.class);
                    if (statesPostEntity.getCode().equals(Constant.Strings.SUC)) {
                        if (action == 1) {
                            ToastUtil.initToast(mContext, "关房成功");
                        } else {
                            ToastUtil.initToast(mContext, "保存成功");
                        }
                        onBtnClickListener.onBtnClick(isClose);
                        dismiss();
                    } else {
                        ToastUtil.initToast(mContext, statesPostEntity.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    private void initStartTime() {
        String[] varStart = DateUtils.long2Data(System.currentTimeMillis()).split("-");
        Calendar selectedDate = Calendar.getInstance();
        selectedDate.set(Integer.parseInt(varStart[0]), Integer.parseInt(varStart[1]) - 1, Integer.parseInt(varStart[2]));

        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                if (isFirst) {
                    mStartDate = format.format(date);
                    mTvTimeMore0.setText(mStartDate);
                    isFirst = false;
                    String[] var = mStartDate.split("-");
                    mDataEndDate = Calendar.getInstance();
                    mDataEndDate.set(Integer.parseInt(var[0]), Integer.parseInt(var[1]) - 1, Integer.parseInt(var[2]));
                    initStartTime();
                } else {
                    mEndDate = format.format(date);
                    mTvTimeMore1.setText("/" + mEndDate);
                    isFirst = true;
                }
                getTimeNum(1);
            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(16) //滚轮文字大小
                .setTitleSize(16)//标题文字大小
                .setTitleText(isFirst ? "请选择开始时间" : "请选择结束时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(mContext.getResources().getColor(R.color.colorRed))//标题文字颜色
                .setSubmitColor(mContext.getResources().getColor(R.color.colorRed))//确定按钮文字颜色
                .setCancelColor(mContext.getResources().getColor(R.color.colorRed))//取消按钮文字颜色
                .setTitleBgColor(mContext.getResources().getColor(R.color.colorGrayBg))//标题背景颜色 Night mode
                .setBgColor(mContext.getResources().getColor(R.color.colorWhite))//滚轮背景颜色 Night mode
                .setDate(isFirst ? selectedDate : mDataEndDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(isFirst ? selectedDate : mDataEndDate, null)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
//        pvTime.setOnDismissListener(new com.bigkoo.pickerview.listener.OnDismissListener() {
//            @Override
//            public void onDismiss(Object o) {
//                if (isFirst) {
//                    showPopupWindow();
//                }
//            }
//        });

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }

        pvTime.show();
    }


    public void setOnBtnClickListener(OnBtnClickListener onBtnClickListener) {
        this.onBtnClickListener = onBtnClickListener;
    }

    public interface OnBtnClickListener {
        void onBtnClick(boolean isClose);
    }

    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.popular_house_manage);
    }

    @Override
    protected Animation onCreateShowAnimation() {
        return PopularUtil.ShowAnimation();
    }

    @Override
    protected Animation onCreateDismissAnimation() {
        return PopularUtil.dismissAnimation();
    }

}
